<template>
  <a-modal
    :title="'S3'+$t('Key')+$t('Operate')"
    v-model="ekey"
    @cancel="cancelhandle"
    width="48%"
    @ok="subnew"
    :cancelText="$t('Cancel')"
		:okText="$t('Sure')" 
    :maskClosable="false"
    v-dragModal
  >
    <a-table
      :columns="columns"
      :dataSource="keydata"
      bordered
      :pagination="pagination"
      size="small" :locale="defaultSetting">
      <template slot="operation" slot-scope="text, record">
        <a-popconfirm
          v-if="keydata.length"
          :title="$t('Sure-del-tip')"
          :ok-text="$t('Sure')" 
          :cancel-text="$t('Cancel')"
          @confirm="() => onDelete(record)"
        >
          <a href="javascript:;">{{$t('Delete')}}</a>
        </a-popconfirm>
      </template>
    </a-table>

    <a-button class="editable-add-btn" @click="handleAdd">{{$t('Add')}}S3{{$t('Key')}}</a-button>

    <div id="components-form-demo-advanced-search" v-if="flag">
      <a-spin size="large" style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%" tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
      <a-form :form="form" class="ant-advanced-search-form">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('User')+$t('Name')" has-feedback v-bind="formlayout">
              <a-select
                v-decorator="['user',{
                rules:[{required:true,message:$t('Choose')+$t('User')+$t('Name')}]
            }]" :placeholder="$t('Choose')+$t('User')+$t('Name')"
              >
              <!-- {pattern:/^[a-zA-Z][a-zA-Z0-9_]{2,15}$/,message: $t('Not_enter_special_characters')} -->
                <a-select-option v-for="(item,index) in basedata" :value="item" :key="index">{{item}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label has-feedback>
              <a-checkbox @change="onChangekey">{{$t('Automatically-key')}}</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="auto == false">
          <a-col :span="12">
            <a-form-item label="Access key" has-feedback>
              <a-input
                v-decorator="['key',{
                    rules:[{required:true,message:$t('Enter')+$t('Access-key')},
                    {pattern:/^[A-Za-z][A-Za-z0-9]{5,63}$/,message:$t('Key_format')}]
                }]"
                :placeholder="$t('Enter')+$t('Access-key')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Secret key" has-feedback>
              <a-input
                v-decorator="['crt',{
                    rules:[{required:true,message:$t('Enter')+$t('Secret-key')},
                    {pattern:/^[A-Za-z][A-Za-z0-9]{5,63}$/,message:$t('Key_format')}]
                }]"
                :placeholder="$t('Enter')+$t('Secret-key')"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="sureadd">{{ $t('Add') }}</a-button>
            <a-button type="default" :style="{ marginLeft: '8px' }" @click="handleReset">{{ $t('Clear') }}</a-button>
            <!-- <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="flag=false">{{ $t('Finished') }}</a> -->
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import request from '@/request/request'

export default {
  props: ["kk", "tarname"],
  components: { EmptyData },
  data() {
    return {
      form: this.$form.createForm(this),
      formlayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 14 }
      },
      ekey: false,
      auto: false,
      keydata: [],
      basedata: [],
      columns: [
        {
          title: this.$t('User'),
          dataIndex: "user",
          key: "user",
          // width: "20%",
          scopedSlots: { customRender: "user" }
        },
        {
          title: this.$t('Access-key'),
          dataIndex: "access_key",
          key: "access_key",
          // width: "30%",
          scopedSlots: { customRender: "access_key" }
        },
        {
          title: this.$t('Secret-key'),
          dataIndex: "secret_key",
          key: "secret_key",
          // width: "30%",
          scopedSlots: { customRender: "secret_key" }
        },
        {
          title: this.$t('Operate'),
          dataIndex: "operation",
          key: "operation",
          scopedSlots: { customRender: "operation" }
        }
      ],
      pagination: {
        defaultPageSize: 5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger: true,
        pageSizeOptions: ["5", "15", "20", "25"],
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      perdata: ["read", "write", "readwrite", "full"],
      flag: false,
      spinning:false,
      defaultSetting: {emptyText:<EmptyData />}
    };
  },
  watch: {
    kk(val) {
      this.ekey = val;
    },
    tarname(val) {
      this.keydata = val.keys;
      this.basedata = [];
      for (const item of val.subusers) {
        this.basedata.push(item.id);
      }
      // this.basedata.push(val.name);
      this.basedata.push(val.user_id);
    },
    getlanguage(val){
			this.columns=[
				{ title: this.$t('User'),dataIndex: "user",key: "user",scopedSlots: { customRender: "user" }
          // width: "20%",
        },
        { title: this.$t('Access-key'),dataIndex: "access_key",key: "access_key",scopedSlots: { customRender: "access_key" }
          // width: "30%",
        },
        { title: this.$t('Secret-key'),dataIndex: "secret_key",key: "secret_key",scopedSlots: { customRender: "secret_key" }
          // width: "30%",
        },
        { title: this.$t('Operate'),dataIndex: "operation",key: "operation",scopedSlots: { customRender: "operation" } }
			]
		}
  },
  methods: {
    getsubdata() {
      request('get', "rgw/user")
        .then(res => {
          if(res.data.flag == 1) {
            this.model(res.data.id) //返回模板
            this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
          }else {
            for (const item of res.data) {
              if(this.tarname.user_id == item.user_id){
                this.keydata = item.keys;
              }
            }
          }
        });
    },
    cancelhandle(e) {
      this.form.resetFields();
      // this.ekey = false;
      this.auto = false;
      this.spinning=false
      this.flag = false;
      this.$emit("omodal", false, true);
    },
    subnew(e) {
    //   e.preventDefault();
    //   this.form.validateFields((err, value) => {
    //     if (!err) {
          // this.model(res.data.id) //返回模板
          // this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
					// this.gettask()  //任务栏信息
          this.form.resetFields();
          // this.ekey = false;
          this.auto = false;
          this.flag = false;
          this.$emit("omodal", false, false);
    //     }
    //   });
    },

    handleAdd() {
      this.flag = true;
    },
    onChangekey(e) {
      if (e.target.checked) {
        this.auto = true;
      } else {
        this.auto = false;
      }
    },
    sureadd(e) {
      e.preventDefault();
      this.form.validateFields((err, value) => {
        if (!err) {
          this.spinning = true
          request('put', "rgw/user/key/", {
            // .post(this.allurl + "rgw/user/s3", {
              // user: this.tarname.user_id,
              // subuser: value.user,
              user: value.user,
              generate: this.auto,
              key: value.key,
              crt: value.crt
            })
            .then(res => {
              this.form.resetFields();
              this.spinning = false
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              // this.gettask()  //任务栏信息
              this.getsubdata() //刷新数据
            });
        }
      });
    },
    handleReset() {
      this.form.resetFields();
    },
    onDelete(key) {
      let index = 0;
      let paramsData = {};
      index = key.user.indexOf(':');
      if(index != -1) {
        paramsData = {
          subuser: key.user,
          key: key.access_key
        }
      }else {
        paramsData = {
          user: key.user,
          key: key.access_key
        }
      }
      request('DELETE', "rgw/user/key/",
        // .delete(this.allurl + "rgw/user/s3", {
          // data: {
          //   user: this.tarname.user_id,
          //   subuser: key.user,
          //   key: key.access_key
          // }
          // data: paramsData
          paramsData
        )
        .then(res => {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
          // this.gettask()  //任务栏信息
          if (res.data.flag == 0) {
            this.getsubdata() //刷新数据
            const newData = [...this.keydata];
            this.keydata = newData.filter(item => item !== key);
          }
        });
      
    }
  }
};
</script>

<style scoped>

.ant-select {
  width: 100% !important;
}
.client {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.subtn {
  margin-right: 1em;
  margin-top: 0.3em;
}
.add {
  overflow: hidden;
  border: 3px solid #e6f4ff;
  padding-top: 1em;
}
.ant-form-item-label {
  /*width: 35% !important;*/
}

.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}
#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}
</style>
